import wtforms
from wtforms.validators import Email, Length, EqualTo
from app.models import Login, EmailCaptchaModel
from app.exts import database


class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message="验证码格式错误")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误")])
    password_confirm = wtforms.StringField(validators=[Length(min=6, max=20, message="确认密码需要和密码完全相同")])
    # password_confirm = wtforms.StringField(validators=[EqualTo("password", message="确认密码需要和密码完全相同")])

    # 自定义
    # 邮箱不能被重复注册
    def validate_email(self, field):
        email = field.data
        print(f"validate_email:email = {email}")
        login = Login.query.filter_by(email=email).first()
        if login:
            raise wtforms.ValidationError(message="该邮箱已被注册")

    # 验证码是否正确
    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        print(f"validate_captcha:captcha = {captcha}")
        print(f"validate_captcha:email = {email}")
        email_captcha = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        print("------------------------------------------")
        print(email_captcha.email)
        print(email_captcha.captcha)
        if not email_captcha:
            raise wtforms.ValidationError(message="邮箱或验证码错误")
        else:
            database.session.delete(email_captcha)
            database.session.commit()

    # 确认密码与密码完全相同
    def validate_confirm(self, field):
        password_confirm = field.data
        password = self.password.data
        print(password_confirm)
        print(password)
